package com.sx.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ImageUtils {

    /**
     * 图片剪切
     * @param bufferedImage
     * @param startX
     * @param startY
     * @param endX
     * @param endY
     * @return
     */
    public static BufferedImage cropImage(BufferedImage bufferedImage, int startX, int startY, int endX, int endY) {
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        if (startX == -1) {
            startX = 0;
        }
        if (startY == -1) {
            startY = 0;
        }
        if (endX == -1) {
            endX = width - 1;
        }
        if (endY == -1) {
            endY = height - 1;
        }
        BufferedImage result = new BufferedImage(endX - startX, endY - startY, 4);
        for (int x = startX; x < endX; ++x) {
            for (int y = startY; y < endY; ++y) {
                int rgb = bufferedImage.getRGB(x, y);
                result.setRGB(x - startX, y - startY, rgb);
            }
        }
        return result;
    }

    /**
     * 生成图形验证码
     * @param code
     * @param width
     * @param height
     * @return
     */
    public static byte[] generateImageVerify(String code,int width,int height) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = null;
        Graphics graphics = null;
        try {
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            graphics = image.getGraphics();
            graphics.setColor(new Color(255, 255, 255));
            graphics.fillRect(0, 0, width, height);
            char[] chars = code.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                char c = chars[i];
                graphics.setColor(new Color(0, 0, 0));
                graphics.setFont(new Font("Times New Roman", Font.BOLD, 25));
                graphics.drawString(c + "", 15 * i + 10, 20);
            }
            for (int i = 0; i < 5; i++) {
                int x1 = (int) (Math.random() * width);
                int y1 = (int) (Math.random() * height);
                int x2 = (int) (Math.random() * width);
                int y2 = (int) (Math.random() * height);
                graphics.setColor(new Color(0, 0, 0));
                graphics.drawLine(x1, y1, x2, y2);
            }
            byteArrayOutputStream=new ByteArrayOutputStream();
            ImageIO.write(image, "png", byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();
        }finally {
            if(graphics==null)  graphics.dispose();
            try {
                if (byteArrayOutputStream == null) byteArrayOutputStream.close();
            }catch (Exception ex){}
        }
    }


}
